import random

from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.core.paginator import Paginator
from myApp.models import User
import hashlib
from .utils import (getHomeData,getSelfInfo,getChangePasswordData,getTableData,getCollectionData,
                    getSalaryChartData,getCompanyChartData,getEducationalData,getCompanyStatusData,getAddressChartData)
from . import word_cloud_picture

# Create your views here.
def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')

    uname = request.POST.get('username')
    pwd = request.POST.get('password')
    if not uname or not pwd:
        return render(request, 'login.html', {'error_message': '用户名和密码不能为空！'})

    md5 = hashlib.md5()
    md5.update(pwd.encode())
    pwd = md5.hexdigest()
    try:
        user = User.objects.get(username=uname, password=pwd)
        request.session['username'] = user.username
        return redirect('/myApp/home')
    except User.DoesNotExist:
        return render(request, 'login.html', {'error_message': '用户名或密码错误'})

def registry(request):
    if request.method == 'GET':
        return render(request,'registry.html')

    uname = request.POST.get('username')
    pwd = request.POST.get('password')
    checkPwd = request.POST.get('checkPassword')
    try:
        User.objects.get(username=uname)
    except:
        # 检查用户名、密码和确认密码是否为空
        if not uname or not pwd or not checkPwd:
            return render(request, 'registry.html', {'error_message': '用户名、密码和确认密码不能为空！'})

            # 检查用户名是否已存在
        try:
            User.objects.get(username=uname)
            return render(request, 'registry.html', {'error_message': '该用户名已存在，请选择其他用户名！'})
        except User.DoesNotExist:
            # 检查密码和确认密码是否一致
            if pwd != checkPwd:
                return render(request, 'registry.html', {'error_message': '两次密码输入不一致，请重新输入！'})

                # 如果一切检查通过，可以创建用户
            md5 = hashlib.md5()
            md5.update(pwd.encode())
            pwd = md5.hexdigest()
            User.objects.create(username=uname, password=pwd)
            return redirect('/myApp/login')

def home(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    year,month,day = getHomeData.getNowTime()
    userCreateData = getHomeData.getUserCreateTime()
    top6Users = getHomeData.getUserTop6()
    jobsLen,usersLen,educationTop,salaryTop,salaryMonthTop, addressTop, internshipMax = getHomeData.getAllTags()
    jobPBarData = getHomeData.getAllJobsPBar()
    tableData = getHomeData.getTableData()
    return render(request,'index.html',{
        'userInfo':userInfo,
        'dateInfo':{'year':year,'month':month,'day':day},
        'userCreateData':userCreateData,
        'top6Users':top6Users,
        'tagDic':{
            'jobsLen':jobsLen,
            'usersLen':usersLen,
            'educationTop':educationTop,
            'salaryTop':salaryTop,
            'salaryMonthTop':salaryMonthTop,
            'addressTop':addressTop,
            'internshipMax':internshipMax
        },
        'jobPBarData':jobPBarData,
        'tableData':tableData
    })

def logOut(request):
    request.session.clear()
    return redirect('login')

def selfInfo(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    educations, workExperience, jobList = getSelfInfo.getPageData()
    if request.method == 'POST':
        getSelfInfo.changeSelfInfo(request.POST,request.FILES)
        userInfo = User.objects.get(username=uname)
    return render(request,'selfInfo.html',{
        'userInfo':userInfo,
        'pageData': {
            'educations': educations,
            'workExperience': workExperience,
            'jobList': jobList
        },

    })

def changePassword(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    error_message = None
    if request.method == 'POST':
        error_message = getChangePasswordData.changePassword(userInfo,request.POST)
        userInfo = User.objects.get(username=uname)
    return render(request, 'changePassword.html', {
        'userInfo': userInfo,
        'error_message':error_message
    })

def tableData(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    tableData = getTableData.getTableData()
    paginator = Paginator(tableData,10)
    cur_page = 1
    if request.GET.get('page'):
        cur_page = int(request.GET.get('page'))
    c_page = paginator.page(cur_page)

    page_range = []
    visibleNumber = 10
    min = int(cur_page - visibleNumber / 10)
    if min < 1:
        min = 1
    max = min + visibleNumber
    if max > paginator.page_range[-1]:
        max = paginator.page_range[-1]
    for i in range(min,max):
        page_range.append(i)
    return render(request,'tableData.html',{
        'userInfo':userInfo,
        'c_page':c_page,
        'page_range':page_range,
        'paginator':paginator
    })

def collectionTableData(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    collectionData = getCollectionData.getCollectionData(userInfo)
    return render(request,'collectionTableData.html',{
        'userInfo':userInfo,
        'collectionData':collectionData
    })

def addCollection(request,jobId):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    getCollectionData.addCollection(userInfo,jobId)
    return redirect('collectionTableData')

def removeCollection(request,colId):
    getCollectionData.removeCollection(colId)
    return redirect('collectionTableData')

def salary(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    educations,workExperience = getSalaryChartData.getPageData()
    defaultEducations = '不限'
    defaultWorkExperience = '不限'
    if request.GET.get('educational'):defaultEducations = request.GET.get('educational')
    if request.GET.get('workExperience'):defaultWorkExperience = request.GET.get('workExperience')
    salaryList, barData, legends = getSalaryChartData.getBarData(defaultEducations,defaultWorkExperience)
    pieData = getSalaryChartData.pieData()
    louDouData = getSalaryChartData.getLouDouData()
    return render(request,'salaryChart.html',{
        'userInfo':userInfo,
        'educations':educations,
        'workExperience':workExperience,
        'defaultEducations':defaultEducations,
        'defaultWorkExperience':defaultWorkExperience,
        'salaryList':salaryList,
        'barData':barData,
        'legends':legends,
        'pieData':pieData,
        'louDouData':louDouData
    })

def company(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    typeList = getCompanyChartData.PageData()
    type = 'all'
    if request.GET.get('type'): type = request.GET.get('type')
    rowData, columnData = getCompanyChartData.getCompanyBar(type)
    pieData = getCompanyChartData.getCompanyPie(type)
    companyPeople, lineData = getCompanyChartData.getCompanyPeople(type)
    return render(request,'companyChart.html',{
        'userInfo':userInfo,
        'typeList':typeList,
        'type':type,
        'rowData':rowData,
        'columnData':columnData,
        'pieData':pieData,
        'companyPeople':companyPeople,
        'lineData':lineData
    })

def companyTags(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    return render(request, 'companyTags.html', {
        'userInfo': userInfo,

    })

def educational(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    educations = getEducationalData.getPageData()
    defaultEducations = '不限'
    if request.GET.get('educational'): defaultEducations = request.GET.get('educational')
    workExperience,ColumnOne,ColumnTwo,hasEmpty = getEducationalData.getExperienceData(defaultEducations)
    barDataRow,barDataColumn = getEducationalData.getPeopleData()
    return render(request, 'educationalChart.html', {
        'userInfo': userInfo,
        'educations': educations,
        'defaultEducations':defaultEducations,
        'workExperience': workExperience,
        'ColumnOne': ColumnOne,
        'ColumnTwo':ColumnTwo,
        'hasEmpty': hasEmpty,
        'barDataRow': barDataRow,
        'barDataColumn':barDataColumn
    })

def companyStatus(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    typeList = getCompanyStatusData.getPageData()
    defaultType = '不限'
    if request.GET.get('JobType'): defaultType = request.GET.get('JobType')
    technologyRow,technologyColumn = getCompanyStatusData.getTechData(defaultType)
    companyStatusData = getCompanyStatusData.getCompanyStatusData()
    return render(request, 'companyStatus.html', {
        'userInfo': userInfo,
        'typeList': typeList,
        'defaultType': defaultType,
        'technologyRow': technologyRow,
        'technologyColumn':technologyColumn,
        'companyStatusData':companyStatusData
    })

def address(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    hotCities = getAddressChartData.getPageData()
    defaultCity = '北京'
    if request.GET.get('city'): defaultCity = request.GET.get('city')
    salaryRows,salaryColumn = getAddressChartData.getSalaryData(defaultCity)
    companyPeopleData = getAddressChartData.getCompanyPeopleData(defaultCity)
    educationData = getAddressChartData.getEducationData(defaultCity)
    distData = getAddressChartData.getDistData(defaultCity)
    randomPicture = random.randint(1,1000000)
    word_cloud_picture.get_img('companyTags','./static/3.png','./static/addressCTags'+str(randomPicture)+'.png')
    return render(request, 'addressChart.html', {
        'userInfo': userInfo,
        'hotCities':hotCities,
        'defaultCity':defaultCity,
        'salaryRows':salaryRows,
        'salaryColumn':salaryColumn,
        'companyPeopleData':companyPeopleData,
        'educationData':educationData,
        'distData':distData,
        'url':randomPicture
    })